#include <QTimer>
#include <QDateTime>
#include <QSqlQuery>
#include <QSqlError>
#include <QVariant>
#include <QDebug>
#include "datamining.h"
//#include "macro.h"

DataMining::DataMining(QString parDBOConName, QSqlQuery *parSqlQuery, QObject *parent):
    QObject(parent)
{
    dboConnectionName=parDBOConName;
    slotTimerEventMiningData();
}

void DataMining::slotTimerEventMiningData()
{
    emit sigInfo("Mining Sensor Data @ "+QDateTime::currentDateTime().toString());
    QDateTime lastUpdatedTime, lastToUpdateTime;
    QSqlQuery quryTemp(QSqlDatabase::database(dboConnectionName));
    QSqlQuery quryTemp2(QSqlDatabase::database(dboConnectionName));
    QSqlQuery quryTemp3(QSqlDatabase::database(dboConnectionName));


    if(!quryTemp.exec("select max(LastUpdatedTime) from HistorySensorData"))
    {
        emit sigInfo("Fail to select max lastupdatetime from historysensordata"+
                     quryTemp.lastError().text());
        return;
    }
    else if(quryTemp.next()&&!quryTemp.value(0).isNull())
    {
        lastUpdatedTime.setDate(quryTemp.value(0).toDateTime().date());
    }
    else
        lastUpdatedTime=QDateTime::currentDateTime().addYears(-100); //100年以前

    lastToUpdateTime.setDate(QDate::currentDate());

    if(quryTemp.exec("select DateTimeStart,DateTimeEnd,TableName from "
         " SensorDataIndex where DateTimeEnd>"+lastUpdatedTime.toString("yyyyMMddhhmmss")+
          " and DateTimeEnd<="+lastToUpdateTime.toString("yyyyMMddhhmmss")))
    {
        QDateTime dtStart,dtEnd;
        QString tableName;
        double maxData,minData,stdDevData,avgData;
        qint64 nodeMacAddr;
        qint32 countData;
        qint16 sensorID;
        while(quryTemp.next())
        {
            dtStart=quryTemp.value(0).toDateTime();
            dtEnd=quryTemp.value(1).toDateTime();
            tableName=quryTemp.value(2).toString();
            emit sigInfo("Begin to mine "+tableName);
            if(quryTemp2.exec("select NodeMacAddress,SensorID,max(SensorData-0.0),"
                 "min(SensorData-0.0),stddev(SensorData-0.0),avg(SensorData-0.0),count(ID) "
                             "from "+tableName+" group by NodeMacAddress,SensorID"))
            {
                while(quryTemp2.next())
                {
                    nodeMacAddr=quryTemp2.value(0).toLongLong(); sensorID=quryTemp2.value(1).toInt();
                    maxData=quryTemp2.value(2).toDouble(); minData=quryTemp2.value(3).toDouble();
                    stdDevData=quryTemp2.value(4).toDouble(); avgData=quryTemp2.value(5).toDouble();
                    countData=quryTemp2.value(6).toInt();

                    if(!quryTemp3.exec("insert into HistorySensorData(NodeMacAddress,SensorID,DateTimeStart,"
                        "DateTimeEnd,MaxSensorData,MinSensorData,StdDevSensorData,AVGSensorData,CountSensorData) "
                         "values("+QString::number(nodeMacAddr,10)+","+QString::number(sensorID,10)+",'"+
                           dtStart.toString("yyyyMMddhhmmss")+"','"+dtEnd.toString("yyyyMMddhhmmss")+"','"+QString::number(maxData)+
                            "','"+QString::number(minData)+"','"+QString::number(stdDevData)+"','"+QString::number(avgData)+"',"+
                                       QString::number(countData,10)+")"))
                        emit sigInfo("Fail to insert into historysensordata"+quryTemp3.lastError().text());
                }
            }
            else
                emit sigInfo("Fail to select in SensorDataMining::slotTimerEventMiningData"+quryTemp2.lastError().text());

        }
    }
    else
        emit sigInfo("Fail to select in SensorDataMining::slotTimerEventMiningData"+quryTemp.lastError().text());

    emit sigInfo(".......Mining completed........");

    QTime time24(23,59,59,999);
    qint64 msBefore24=QTime::currentTime().msecsTo(time24)+5000; //保证超过了24小时
    if(msBefore24<1)
        msBefore24=2000;
    QTimer::singleShot(msBefore24,this,SLOT(slotTimerEventMiningData()));
}
